import AbstractCat2DocFile from "./file";
import markdown from 'markdown-it';
import TurndownService from 'turndown';
import { gfm } from 'turndown-plugin-gfm'
class C2dMarkdown extends AbstractCat2DocFile {
    /** 获取文件扩展名 */
    getExtension(){
        return "MD"
    }
    /** 导出文件 */
    export(fileName, element) {
        return new Promise((resolve,reject)=> {
            try {
                const turndownService = new TurndownService();
                turndownService.use(gfm)
                const md = turndownService.turndown(element.innerHTML);
                let blob = new Blob([md], { type: 'text/plain' });
                let url = URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                a.remove();
                URL.revokeObjectURL(url); // 释放 URL 对象
                resolve({});
            } catch (err) {
                console.error(err)
                reject(err)
            }
        });
    }
    /** 导入文件 */
    import(file) {
        return new Promise((resolve,reject)=> {
            try {
                let reader = new FileReader();
                // 读取文件(以纯文本的形式返回文件内容)
                reader.onload = function (e) {
                    try {
                        if (e.target.result && typeof e.target.result === 'string') {
                            let md = new markdown({
                                html:true,
                                prefix:'c2d-code-'
                            });
                            let html = md.render(e.target.result||'');
                            resolve(html);
                        }
                    } catch (err) {
                        reject(err)
                    }
                }
                reader.readAsText(file, "UTF-8");
            } catch (err) {
                reject(err)
            }
        });
    }
}
export default C2dMarkdown;
